<?php

namespace PHPSpring\Annotation\Impl;

use PHPSpring\Annotation\IValidator;

/**
 * @Pattern(pattern='/MyRegexPattern/i', $message?, array|string $groups?)
 * eg:
 * @Pattern(pattern='/MyRegexPattern/i')
 * @Pattern(pattern='/MyRegexPattern/i', message='message') or @Pattern(pattern='/MyRegexPattern/i', 'message')
 * @Pattern(pattern='/MyRegexPattern/i', message='message', groups='groups') or @Pattern(pattern='/MyRegexPattern/i', 'message', groups='groups')
 * message format: '%s格式不正确' => '$fieldName格式不正确'
 */
class Pattern implements IValidator {
  public static function validate ($args, $fieldName, $fieldType, $fieldValue, $group = null) {
    $error = static::normalizeArguments($args);
    if ($error) {
      return $error;
    }
    if (Validation::skipValidateByGroup($group, $args)) {
      return;
    }
    $pattern = $args['pattern'];
    $error = false;
    if (!is_string($fieldValue)) {
      $error = true;
    } else {
      if (!preg_match($pattern, $fieldValue, $matches)) {
        $error = true;
      }
    }
    if ($error) {
      return self::getMessage($fieldName, $fieldValue, $pattern, $args[Validation::MESSAGE_ARG_KEY]);
    }
  }

  public static function normalizeArguments (array &$args) {
    Validation::resetMessageArgs($args, '%s 必填');
    if (empty($args['pattern'])) {
      return '正则表达式验证器参数缺失：$pattern';
    }
    $pattern = $args['pattern'];
    if (strpos($pattern, '/') !== 0) {
      return "正则表达式验证器参数不合法：pattern: {$pattern}";
    }

    return null;
  }

  private static function getMessage ($fieldName, $fieldValue, $pattern, $message) {
    $message = str_replace('%s', $fieldName, $message);

    return $message;
  }

}
